package com.travelingsalesmen.post;

import com.travelingsalesmen.post.file.FilePost;
import com.travelingsalesmen.post.gui.GUIPost;
import java.awt.EventQueue;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UnsupportedLookAndFeelException;

public class Simulator {
    
    public static void main(String[] args) {
        
        final boolean useGui = args.length != 0 && args[0].equals("--gui");
        
        EventQueue.invokeLater(new Runnable() {
            
            @Override
            public void run() {
                Store store = new Store();

                // Interface goodness
                IPost post;
                
                if (useGui) {
                    setTheme();
                    post = new GUIPost();
                } else {
                    post = new FilePost();
                }
                
                Manager manager = store.getManager();
                manager.openStore();
                manager.startServer();
                
                try {
                    // Setup the post with server connection
                    manager.buildCatalogOnServer();
                    manager.logPostIntoServer(post);
                    post.getCatalogFromServer();
                } catch (RemoteException remoteException) {
                    // Do things manually if that failed
                    post.setCatalog(manager.buildCatalog());
                } finally {
                    // Then start the server
                    post.start();
                } 
            }
        });
    }
    
    private static void setTheme() {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
